const { Blog, Op } = require('../sequelize/sequelize')

fn_index = async (ctx) => {
    await Blog.findAll().then(res => {
        ctx.body = res
    })
}

fn_data = async (ctx) => {

    let keyword = ctx.request.query.keyword
    if (keyword !== '') {
        if (isNaN(keyword) == false) {
            let data = await Blog.findAll({
                where: {
                    [Op.or]: [
                        { id: keyword },
                        { headline: keyword },
                        { abstract: keyword },
                        { content: keyword },
                        { classify: keyword },
                        { author: keyword },
                    ]
                }
            })
            ctx.body = data
        } else {
            let data = await Blog.findAll({
                where: {
                    [Op.or]: [
                        { headline: keyword },
                        { abstract: keyword },
                        { content: keyword },
                        { classify: keyword },
                        { author: keyword },
                    ]
                }
            })
            ctx.body = data
        }
    }
    else {
        await Blog.findAll().then(res => {
            ctx.body = res
        })
    }
}

fn_add = async(ctx)=>{

    let data =ctx.request.body

    await Blog.create(data)

    await Blog.findAll().then(res=>{
        ctx.body=res
    })
}

fn_edit= async(ctx)=>{
    let data = ctx.request.body

    await Blog.findByPk(data.id).then(async(post)=>{
        await post.update(
            {
                id:data.id,
                headline:data.headline,
                abstract:data.abstract,
                content:data.content,
                classify:data.classify,
                author:data.author,
                issuedate:data.issuedate

            }
        )
    })

    await Blog.findAll().then(res=>{
        ctx.body = res
    })
}

fn_Delete = async(ctx)=>{
    let id = ctx.request.query.id

    await Blog.destroy({
        where:{id:id}
    })
    await Blog.findAll().then(res=>{
        ctx.body=res
    })
}

let get =  [['/index',fn_index],['/data',fn_data],['/indexDeleted',fn_Delete]]
let post= [['/indexadd',fn_add],['/indexedit',fn_edit]]

module.exports={
    'GET':get,
    'POST':post
}